package org.rain.core.mp.config;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpServletResponseWrapper;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * created by yangtong on 2025/4/10 23:54:18
 */
public class DruidAdRemoveFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletResponse httpResp = (HttpServletResponse) response;
        CharResponseWrapper responseWrapper = new CharResponseWrapper(httpResp);

        chain.doFilter(request, responseWrapper);

        String content = responseWrapper.toString();

        // 清除广告 HTML（使用正则或关键词查找）
        content = content.replaceAll("<footer[\\s\\S]*?</footer>", "");

        // 写回原始 response
        PrintWriter out = httpResp.getWriter();
        out.write(content);
        out.flush();
    }

    // 包装类
    private static class CharResponseWrapper extends HttpServletResponseWrapper {
        private final StringWriter sw = new StringWriter();

        public CharResponseWrapper(HttpServletResponse response) {
            super(response);
        }

        @Override
        public PrintWriter getWriter() {
            return new PrintWriter(sw);
        }

        @Override
        public String toString() {
            return sw.toString();
        }
    }

}
